package cn.kgc.service.impl;

import cn.kgc.common.dtoutils.dtoUtil;
import cn.kgc.common.redisutils.stringRedisTemplateUtil;
import cn.kgc.dao.mapper.*;
import cn.kgc.dtos.Dto;
import cn.kgc.pojo.*;
import cn.kgc.service.ItripLabelDicService;
import cn.kgc.vo.*;
import com.alibaba.fastjson.JSONObject;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.slf4j.Logger;
import org.springframework.mobile.device.Device;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Service
public class ItripLabelDicServiceImpl implements ItripLabelDicService {
    @Resource
    ItripLabelDicMapper itripLabelDicMapper;
    @Resource
    ItripImageMapper itripImageMapper;
    @Resource
    ItripCommentMapper itripCommentMapper;
    @Resource
    ItripHotelRoomMapper itripHotelRoomMapper;
    @Resource
    ItripAreaDicMapper itripAreaDicMapper;
    @Resource
    ItripHotelOrderMapper itripHotelOrderMapper;
    @Resource
    private stringRedisTemplateUtil stringRedisTemplateUtil;
    @Resource
    private ItripHotelTempStoreMapper itripHotelTempStoreMapper;
    @Resource
    private ItripHotelMapper itripHotelMapper;
    @Resource
    private ItripUserLinkUserMapper itripUserLinkUserMapper;

    @Override
    public Dto getTravelType() {
        //获取旅游类型列表成功
        List<ItripLabelDic> itripLabelDicList = itripLabelDicMapper.selectTravelType();
        return dtoUtil.getDto("0", "获取旅游类型列表成功", itripLabelDicList, "true", null);
    }

    @Override
    public Dto getImg(String id) {
        //判断id是否为空
        if (null != id && "" != id) {
            //获取酒店图片
            List<ItripImage> imgList = itripImageMapper.selectImg(Long.parseLong(id));
            return dtoUtil.getDto("0", "获取酒店图片", imgList, "true", null);
        }
        return dtoUtil.getDto("10005", "获取酒店图片失败", "", "false", null);
    }

    @Override
    public Dto getHotelDesc(String id) {
        //判断id是否为空
        if (null != id && "" != id) {
            //获取酒店信息
            ItripHotel itripHotel = itripCommentMapper.queryHotelDetails(Long.parseLong(id));
            return dtoUtil.getDto("0", "获取酒店信息", itripHotel, "true", null);
        }
        return dtoUtil.getDto("10005", "获取酒店信息失败", "", "false", null);
    }

    @Override
    public Dto upLoad(MultipartFile file, HttpServletRequest request) {
        //文件是否存在
        if(!file.isEmpty()){
            //获取token
            String token=request.getHeader("token");
            //根据获取的key获取redis中对应的value
            String key=stringRedisTemplateUtil.getKey(token);
            //把JSON转换成ItripUser对象
            ItripUser user= JSONObject.parseObject(key,ItripUser.class);
            //获取userid
            long id = user.getId();
            //获取当前时间
            long time = System.currentTimeMillis();
            //随机数
            Random ra =new Random();
            String random = "";
            //生产随机数
            for (int i = 0; i < 7; i++) {
                random+= ra.nextInt(10);
            }
            //生产图片名
            String imgname = id + "-" + time +"-"+ random;
            String path = request.getSession().getServletContext().getRealPath("/data1/uploadimg/comment");
            //"http://img.itrip.project.bdqn.cn/comment";
            //定义文件
            File parent = new File(path);
            if (!parent.exists()) {
                parent.mkdirs();
            }
            String filename = file.getOriginalFilename();
            String prefix=filename.substring(filename.lastIndexOf(".")+1);
            imgname += imgname + "." + prefix;
            File files = new File(path,imgname);
            try {
                file.transferTo(files);
            } catch (IOException e) {
                e.printStackTrace();
            }
            List imglist = new ArrayList();
            imglist.add(imgname);
            return dtoUtil.getDto("0", "图片添加成功", imglist, "false", null);
        }else{
            return  dtoUtil.getDto("0", "图片添加失败", "", "false", null);
        }
    }

    @Override
    public Dto addComment(CommentVo commentVo,HttpServletRequest request) {
        String token=request.getHeader("token");
        //根据获取的key获取redis中对应的value
        String key=stringRedisTemplateUtil.getKey(token);
        //把JSON转换成ItripUser对象
        ItripUser user= JSONObject.parseObject(key,ItripUser.class);
        //获取用户id
        long id = user.getId();
        commentVo.setId(id);
        //获取总评分
        long score = commentVo.getFacilitiesScore()+commentVo.getHygieneScore()+commentVo.getPositionScore()+commentVo.getServiceScore();
        //设置总评分
        commentVo.setScore(score/4==0?score/4:score/4+score%4);
        //添加评论
        int result = itripCommentMapper.insert(commentVo);
        //获取当前id
        long commentID = itripCommentMapper.getCommentID();
        String path = request.getSession().getServletContext().getRealPath("/data1/uploadimg/comment");
        if (0<result && 0<commentVo.getItripImages().size()) {
            int i = 1;
            //便利添加图片信息
            for (Object imgurl: commentVo.getItripImages()) {
                ItripImage itripImage = new ItripImage();
                String url = imgurl.toString();
                url = url.substring(8);
                url = url.substring(0,url.length()-1);
                itripImage.setImgUrl(path+"\\"+url);
                itripImage.setCreatedBy(id);
                itripImage.setType("2");
                itripImage.setPosition(i);
                itripImage.setTargetId(commentID);
                itripImageMapper.insert(itripImage);
                i++;
            }
        }
        //修改当前订单状态
        long results = itripHotelOrderMapper.updateOrderStatus(commentVo.getOrderId());
        if (results!=0) {
            return dtoUtil.getDto("0", "点评成功", null, "true", null);
        }
        return dtoUtil.getDto("0", "点评失败", null, "true", null);
    }

    @Override
    public Dto selectHotelFeature() {
        //获取酒店特色
        List<ItripLabelDic> labelDics = itripLabelDicMapper.selectHotelFeature();
        return dtoUtil.getDto("0", "酒店特色", labelDics, "true", null);
    }

    @Override
    public Dto queryHotcity(String id) {
        if (null != id && "" != id) {
            //获取所有省或市的信息
            List<ItripAreaDic> itripAreaDics = itripAreaDicMapper.selectHotcity(Long.parseLong(id));
            return dtoUtil.getDto("0", "获取所有省或市的信息", itripAreaDics, "true", null);
        }
        return dtoUtil.getDto("0", "id不能为空", "", "false", null);
    }

    @Override
    public Dto queryTradearea(String parent) {
        if (null != parent && "" != parent) {
            //查出商圈
            List<ItripAreaDicVo> itripAreaDics = itripAreaDicMapper.selectTradearea(Long.parseLong(parent));
            return dtoUtil.getDto("0", "查出商圈", itripAreaDics, "true", null);
        }
        return dtoUtil.getDto("0", "父的主键不能为空", "", "false", null);
    }

    @Override
    public Dto queryHotelRoombed() {
        //床型
        List<ItripLabelDic> itripLabelDics = itripLabelDicMapper.selectHotelRoombed();
        if (null!=itripLabelDics) {
            return dtoUtil.getDto("0", "床型", itripLabelDics, "true", null);
        }
        return dtoUtil.getDto("0", "没有床型", itripLabelDics, "false", null);
    }

    @Override
    public Dto getCount(String id) {
        if (null != id) {
            //当前评论是否有图片数量
            long havingimg = itripCommentMapper.getIsHavingImg(Long.parseLong(id));
            //当前评论有待改善 数量
            long improve = itripCommentMapper.getisOkNO(Long.parseLong(id));
            //获取当前评论值得推荐数量
            long isOk = itripCommentMapper.getisOkYES(Long.parseLong(id));
            //获取当前评论数量
            long allCount = itripCommentMapper.getAllCount(Long.parseLong(id));
            ItripCommentVo itripCommentVo = new ItripCommentVo();
            itripCommentVo.setIsok(isOk);
            itripCommentVo.setAllcomment(allCount);
            itripCommentVo.setHavingimg(havingimg);
            itripCommentVo.setImprove(improve);
            return dtoUtil.getDto("0", "评论数量", itripCommentVo, "true", null);
        }
        return dtoUtil.getDto("0", "id不能为空", "", "false", null);
    }

    @Override
    public Dto getCommentList(QueryComment queryComment) {
        ItripCommentPage itripCommentPage = new ItripCommentPage();
        //评论总数
        long count = itripCommentMapper.selectCommentCount(queryComment);
        //总数
        long size = queryComment.getPageSize();
        //页数
        long curPage = count%size==0?count/size:count/size+1;
        itripCommentPage.setTotal(count);
        itripCommentPage.setPageCount(curPage);
        itripCommentPage.setCurPage(queryComment.getPageNo());
        itripCommentPage.setBeginPos((queryComment.getPageNo()-1)*size);
        itripCommentPage.setPageSize(size);
        itripCommentPage.setQuery(queryComment);
        itripCommentPage.setLimitone((queryComment.getPageNo()-1)*size);
        itripCommentPage.setLimittwo(queryComment.getPageNo()*size);
        //评论列表
        List<CommentListVo> itripComments = itripCommentMapper.selectCommentList(itripCommentPage);
        itripCommentPage.setRows(itripComments);
        return dtoUtil.getDto("0", "评论列表", itripCommentPage, "true", null);
    }

    @Override
    public Dto getHotelScore(String id) {
        //评分列表
        HotelScore hotelScore = itripCommentMapper.getHotelScore(Long.parseLong(id));
        return dtoUtil.getDto("0", "评分列表", hotelScore, "true", null);
    }

    /**
     * 酒店介绍
     * @param id 根据酒店id
     * @return
     */
    @Override
    public Dto queryHotelDetails(String id) {
        ItripHotel itripHotel = itripCommentMapper.queryHotelDetails(Long.parseLong(id));
        ItripLabelDic itripLabelDic=new ItripLabelDic();
        itripLabelDic.setDescription(itripHotel.getDetails());
        List<ItripLabelDic> list= itripLabelDicMapper.selectDesc(Long.parseLong(id));
        list.add(0, itripLabelDic);
        Map<String, String> stringStringMap = new HashMap<>();
        stringStringMap.put("Details",itripHotel.getDetails());

        return dtoUtil.getDto("0", "酒店介绍", list, "true", null);
    }

    /**
     * 酒店设施
     * @param id 根据酒店id
     * @return
     */
    @Override
    public Dto queryHotelFacilities(String id) {
        ItripHotel itripHotel = itripCommentMapper.queryHotelFacilities(Long.parseLong(id));
        return dtoUtil.getDto("0", "酒店设施", itripHotel.getFacilities(), "true", null);
    }

    /**
     * 酒店政策
     * @param id 根据 酒店id
     * @return
     */
    @Override
    public Dto queryHotelPolicy(String id) {
        ItripHotel itripHotel = itripCommentMapper.queryHotelPolicy(Long.parseLong(id));
        return dtoUtil.getDto("0", "酒店政策", itripHotel.getHotelPolicy(), "true", null);
    }

    /**
     * 酒店图片
     * @param id 根据主键
     * @return
     */
    @Override
    public Dto getCommentImg(String id) {
        List<ItripImage> itripImage = itripCommentMapper.getCommentImg(Long.parseLong(id));
        return dtoUtil.getDto("0", "酒店图片",itripImage, "true", null);
    }

    /**
     * 酒店房间
     * @param itripHotelRoom 房间信息
     * @return
     */
    @Override
    public Dto selectByQuery(ItripHotelRoom itripHotelRoom) {
        List<ItripHotelRoom> itripHotelRooms = itripCommentMapper.selectByQuery(itripHotelRoom);
        List data = new ArrayList();
        for (ItripHotelRoom itripHotelRoom1:
        itripHotelRooms) {
            List list = new ArrayList();
            list.add(itripHotelRoom1);
            data.add(list);
        }
        return dtoUtil.getDto("0", "酒店房间",data, "true", null);
    }

    /**
     * 获取酒店图片
     * @param id 酒店id
     * @return
     */
    @Override
    public Dto getHotelRoomImg(String id) {
        if (null != id && "" != id) {
            List<ItripImage> imgList = itripImageMapper.getHotelRoomImg(Long.parseLong(id));
            return dtoUtil.getDto("0", "获取酒店图片", imgList, "true", null);
        }
        return dtoUtil.getDto("10005", "获取酒店图片失败", "", "false", null);
    }

    /**
     * 图片删除成功
     * @param imgName 图片名称
     * @param request
     * @return
     */
    @Override
    public Dto delpic(String imgName,HttpServletRequest request) {
        String path = request.getSession().getServletContext().getRealPath("/data1/uploadimg/comment");
        File file = new File(path,imgName);
        if (file.exists()) {
            file.delete();
            return dtoUtil.getDto("0", "图片删除成功", "", "true", null);
        }
        return dtoUtil.getDto("0", "图片删除失败", "", "true", null);
    }

    /**
     * 获取剩于房间数量
     * @param roomVo 根据酒店id 和房间id
     * @return
     */
    @Override
    public Dto getPreorderInfo(RoomVo roomVo) {
        ItripHotelTempStroeVo itripHotelTempStores = itripHotelTempStoreMapper.getPreorderInfo(roomVo);
        String price = itripHotelRoomMapper.selectAmountByIdandHotelId(roomVo);
        if (price!=null) {
            itripHotelTempStores.setPrice(price);
        }
        return dtoUtil.getDto("0", "获取剩于房间数量", itripHotelTempStores, "true", null);
    }

    /**
     * 预定酒店
     * @param itripHotelOrderVo 酒店基本信息
     * @return
     */
    @Override
    public Dto addHotelOrder(ItripHotelOrderVo itripHotelOrderVo) {
        long bookType = 0;
        itripHotelOrderVo.setOrderStatus(0);
        itripHotelOrderVo.setOrderType(1);
        itripHotelOrderVo.setBookType(bookType);
        //获取酒店名称
        itripHotelOrderVo.setHotelName(itripHotelMapper.selectHotelNameById(itripHotelOrderVo.getHotelId()));
        //生产订单号
        String oderno = UUID.randomUUID().toString();
        oderno = oderno.replace("-","");
        oderno=oderno.substring(0, 28);
        itripHotelOrderVo.setOrderNo(oderno);
        RoomVo roomVo = new RoomVo();
        roomVo.setHotelId(String.valueOf(itripHotelOrderVo.getHotelId()));
        roomVo.setRoomId(String.valueOf(itripHotelOrderVo.getRoomId()));
        //获取 当前酒店房间的金额
        String money = itripHotelRoomMapper.selectAmountByIdandHotelId(roomVo);
        itripHotelOrderVo.setPayAmount(Double.valueOf(money)*itripHotelOrderVo.getCount());
        String name = "";
        long id = 0;
        for (ItripUserLinkUser userLinkUser:
        itripHotelOrderVo.getLinkUser()) {
            id = userLinkUser.getId();
            name+=","+userLinkUser.getLinkUserName();
        }
        name = name.substring(1);
        itripHotelOrderVo.setLinkUserName(name);
        int days = (int) ((itripHotelOrderVo.getCheckOutDate().getTime() - itripHotelOrderVo.getCheckInDate().getTime()) / (1000*3600*24));
        itripHotelOrderVo.setBookingDays(days);
        //获取用户id
        long userid = itripUserLinkUserMapper.selectById(id);
        itripHotelOrderVo.setUserId(userid);
        //添加预定信息
        int result = itripHotelOrderMapper.insert(itripHotelOrderVo);
        //修改库存数量
        itripHotelTempStoreMapper.updatestoreByid(itripHotelOrderVo.getHotelId(),itripHotelOrderVo.getRoomId(),itripHotelOrderVo.getCount());
        if (result == 0) {
            return dtoUtil.getDto("40001", "预定酒店失败", null, "false", null);
        }
        //获取订单信息 根据订单号
        ItripHotelOrder itripHotelOrder = itripHotelOrderMapper.selectOrderByorderNo(itripHotelOrderVo.getOrderNo());
        itripHotelOrderVo.setId(itripHotelOrder.getId());
        return dtoUtil.getDto("40001", "预定酒店", itripHotelOrderVo, "true", null);
    }


}
